package com.sakura.seckill.controller;

import com.sakura.seckill.pojo.User;
import com.sakura.seckill.service.IGoodsService;
import com.sakura.seckill.service.IUserService;
import com.sakura.seckill.vo.DetailVo;
import com.sakura.seckill.vo.GoodsVo;
import com.sakura.seckill.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 商品列表页面
 *
 * @author Sakura
 * @Date 2022-07-27 20:48
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 功能描述：跳转到商品列表
     *
     * 压力测试：15w次  5000*10*3
     * windows优化前QPS：552/s
     *
     * Linus 优化前QPS: 207/s
     * <p>
     *
     * 页面优化：页面缓存
     */
    //produces: 指定响应体返回类型和编码
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {

        //Redis中获取缓存，如果不为空，直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        model.addAttribute("user", user);
        //查询商品信息
        List<GoodsVo> goodsVo = goodsService.findGoodVo();
        model.addAttribute("goodsList", goodsVo);

        // return "goodsList";

        //如果Reids中没有缓存，页面为空，手动渲染，存入Redis并返回
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());

        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        //页面不为空，则将页面缓存到redis中
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }

        return html;
    }

    /**
     * 跳转到商品详情页
     *
     * 页面优化：页面缓存
     */
    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail(Model model, User user, @PathVariable Long goodsId,
                            HttpServletRequest request, HttpServletResponse response) {

        //Redis中获取缓存，如果不为空，则直接返回页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodVoByGoodsId(goodsId);

        //处理秒杀状态
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态  0 > 秒杀倒计时   1 > 秒杀进行中  2 > 秒杀已结束
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        //判断秒杀状态
        if (nowDate.before(startDate)) {
            //秒杀还未开始 secKillStatus = 0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);

        } else if (nowDate.after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        model.addAttribute("remainSeconds", remainSeconds);
        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("goods", goodsVo);

        //如果Redis中没有缓存，页面为空，手动渲染，存入Redis并返回
        WebContext webContext = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        //页面不为空，则将页面缓存到redis中
        if (!StringUtils.isEmpty(html)) {
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;

        // return "goodsDetail";
    }



    /**
     * 跳转到商品详情页
     *
     * 页面静态化
     */
    @RequestMapping("/toDetail2/{goodsId}")
    @ResponseBody
    public RespBean toDetail2(Model model, User user, @PathVariable Long goodsId) {

        //查询商品信息
        GoodsVo goodsVo = goodsService.findGoodVoByGoodsId(goodsId);

        //处理秒杀状态
        Date startDate = goodsVo.getStartDate();
        Date endDate = goodsVo.getEndDate();
        Date nowDate = new Date();
        //秒杀状态  0 > 秒杀倒计时   1 > 秒杀进行中  2 > 秒杀已结束
        int secKillStatus = 0;
        //秒杀倒计时
        int remainSeconds = 0;

        //判断秒杀状态
        if (nowDate.before(startDate)) {
            //秒杀还未开始 secKillStatus = 0
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);

        } else if (nowDate.after(endDate)) {
            //秒杀已结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else {
            //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        DetailVo detailVo=new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setSecKillStatus(secKillStatus);
        detailVo.setRemainSeconds(remainSeconds);

         return RespBean.success(detailVo);
    }


}
